<template>
  <div class="room-list-view">
    <div v-if="loading" class="loading-container">
      <el-skeleton animated :rows="5" />
    </div>

    <div v-else-if="rooms.length === 0" class="empty-container">
      <el-empty description="暂无会议室数据" />
    </div>

    <el-table v-else border :data="rooms" stripe style="width: 100%" @row-click="handleRoomClick">
      <el-table-column label="会议室位置" prop="positionDescription" width="150" />

      <el-table-column label="会议室名称" min-width="150">
        <template #default="{ row }">
          <div class="room-name-cell">
            <span class="room-name">{{ row.roomName }}</span>
            <div class="room-tags">
              <el-tag v-if="isRoomInUse(row)" size="small" type="danger">使用中</el-tag>
              <el-tag v-else size="small" type="success">空闲</el-tag>
              <el-tag v-if="row.isApproval === '1'" size="small" type="warning">需审批</el-tag>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="容量" width="100">
        <template #default="{ row }">
          <div class="capacity-cell">
            <el-icon><user /></el-icon>
            <span>{{ row.capacity || '--' }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="设备" width="180">
        <template #default="{ row }">
          <div class="equipment-tags">
            <template v-if="row.equipment">
              <el-tag v-for="item in formatEquipment(row.equipment)" :key="item" class="equipment-tag" effect="plain" size="small">
                {{ item }}
              </el-tag>
            </template>
            <span v-else>--</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="当日预约" min-width="200">
        <template #default="{ row }">
          <div class="booking-timeline">
            <div v-if="row.activityInfos && row.activityInfos.length > 0" class="timeline">
              <div class="timeline-container">
                <div v-for="hour in workHours" :key="hour" class="timeline-hour" :class="{ 'current-hour': isCurrentHour(hour) }">
                  {{ hour }}:00
                </div>
                <div class="timeline-bar">
                  <div
                    v-for="(activity, index) in row.activityInfos"
                    :key="index"
                    class="timeline-item"
                    :style="getActivityStyle(activity)"
                    :title="`${activity.title}: ${activity.startTime.substr(11, 5)} - ${activity.endTime.substr(11, 5)}`"
                  >
                    <span class="activity-time">{{ activity.startTime.substr(11, 5) }} - {{ activity.endTime.substr(11, 5) }}</span>
                  </div>
                  <div v-if="isToday && showCurrentTimeline" class="current-time-indicator" :style="getCurrentTimePosition()"></div>
                </div>
              </div>
            </div>
            <span v-else>今日暂无预约</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click.stop="handleViewDetail(row)">详情</el-button>
          <!-- <el-button size="small" type="success" @click.stop="handleBookRoom(row)">预约</el-button> -->
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { User } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { computed, ref } from 'vue'
import type { MeetingRoom } from '/@/types/api'

// 定义会议活动类型
interface ActivityInfo {
  id: string
  title: string
  startTime: string
  endTime: string
  [key: string]: any
}

// 定义会议室类型
interface ConferenceRoom {
  id: string | number
  roomName: string
  capacity?: string | number
  positionDescription?: string
  equipment?: string
  isApproval?: string
  activityInfos?: ActivityInfo[]
  [key: string]: any
}

// 组件属性
const props = defineProps<{
  rooms: MeetingRoom[]
  loading: boolean
  currentDate: string
}>()

// 组件事件
const emit = defineEmits<{
  (e: 'bookRoom', room: MeetingRoom): void
  (e: 'viewDetail', room: MeetingRoom): void
  (e: 'row-click', row: MeetingRoom): void
}>()

// 工作时间范围（如 9-18 点）
const workHours = Array.from({ length: 10 }, (_, i) => i + 9)

// 是否为当天（用于显示当前时间指示器）
const isToday = computed(() => {
  return props.currentDate === dayjs().format('YYYY-MM-DD')
})

// 是否显示当前时间线
const showCurrentTimeline = ref(true)

// 检查会议室当前是否在使用中
const isRoomInUse = (room: MeetingRoom) => {
  if (!room.activityInfos || room.activityInfos.length === 0) {
    return false
  }

  const now = new Date()
  // 如果不是今天，永远返回非使用中
  if (!isToday.value) {
    return false
  }

  return room.activityInfos.some((activity) => {
    const startTime = new Date(`${props.currentDate} ${activity.startTime.substr(11, 5)}`)
    const endTime = new Date(`${props.currentDate} ${activity.endTime.substr(11, 5)}`)
    return startTime <= now && now <= endTime
  })
}

// 检查是否是当前小时
const isCurrentHour = (hour: number) => {
  if (!isToday.value) return false
  const currentHour = new Date().getHours()
  return currentHour === hour
}

// 格式化会议室设备
const formatEquipment = (equipment: string) => {
  if (!equipment) return []
  return equipment.split(',')
}

// 获取会议活动在时间轴上的样式
const getActivityStyle = (activity: ActivityInfo) => {
  // 假设工作时间是 9:00-18:00，总共 9 小时
  const workStart = 9
  const workEnd = 18
  const totalHours = workEnd - workStart

  // 活动开始和结束时间
  const startHour = parseInt(activity.startTime.substr(11, 2))
  const startMinute = parseInt(activity.startTime.substr(14, 2))
  const endHour = parseInt(activity.endTime.substr(11, 2))
  const endMinute = parseInt(activity.endTime.substr(14, 2))

  // 相对于工作开始时间的小时数
  const relativeStart = Math.max(0, startHour + startMinute / 60 - workStart)
  const relativeEnd = Math.min(totalHours, endHour + endMinute / 60 - workStart)

  // 计算宽度百分比和左侧位置百分比
  const leftPercent = (relativeStart / totalHours) * 100
  const widthPercent = ((relativeEnd - relativeStart) / totalHours) * 100

  return {
    left: `${leftPercent}%`,
    width: `${widthPercent}%`,
  }
}

// 获取当前时间在时间轴上的位置
const getCurrentTimePosition = () => {
  const now = new Date()
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()

  // 工作时间范围
  const workStart = 9
  const workEnd = 18
  const totalHours = workEnd - workStart

  // 如果当前时间不在工作时间范围内，不显示
  if (currentHour < workStart || currentHour >= workEnd) {
    return { display: 'none' }
  }

  // 计算当前时间相对于工作开始时间的位置百分比
  const relativeTime = currentHour + currentMinute / 60 - workStart
  const leftPercent = (relativeTime / totalHours) * 100

  return {
    left: `${leftPercent}%`,
  }
}

// 点击会议室行
const handleRoomClick = (row: MeetingRoom) => {
  emit('row-click', row)
}

// 查看会议室详情
const handleViewDetail = (room: MeetingRoom) => {
  emit('viewDetail', room)
}

// 预约会议室
const handleBookRoom = (room: MeetingRoom) => {
  emit('bookRoom', room)
}
</script>

<style scoped>
.room-list-view {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 16px;
}

.loading-container,
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.room-name-cell {
  display: flex;
  flex-direction: column;
}

.room-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.room-tags {
  display: flex;
  gap: 5px;
}

.capacity-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.equipment-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.equipment-tag {
  margin-right: 0;
}

.booking-timeline {
  padding: 5px 0;
}

.timeline {
  width: 100%;
}

.timeline-container {
  position: relative;
}

.timeline-hour {
  display: inline-block;
  font-size: 12px;
  color: #909399;
  width: 10%;
}

.timeline-hour.current-hour {
  color: #409eff;
  font-weight: bold;
}

.timeline-bar {
  position: relative;
  height: 24px;
  background-color: #f5f7fa;
  border-radius: 3px;
  margin-top: 5px;
}

.timeline-item {
  position: absolute;
  height: 100%;
  background-color: #e6a23c;
  border-radius: 3px;
  color: #fff;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  min-width: 80px;
  cursor: pointer;
}

.activity-time {
  padding: 0 8px;
}

.current-time-indicator {
  position: absolute;
  top: 0;
  height: 100%;
  width: 2px;
  background-color: #f56c6c;
  z-index: 1;
}
</style>
